﻿/// <summary>
/// Copyright (C) 2007-2010 
/// 数据访问基础类(基于SQLServer)
/// </summary>
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Reflection;
using System.Data.SqlClient;

using Job.Core.Module;
using Job.Core.Data;

namespace Job.Core
{
    /// <summary>
    /// 泛型类 TType为类型参数 where子句用来指定类型约束[接口约束、基类约束、构造函数约束]
    /// 基类约束：指出某个类型必须将指定的类作为基类（或者就是该类本身），才能用作该泛型类型的类型参数。这样的约束一经使用，就必须出现在该类型参数的所有其他约束之前。
    /// 构造函数约束：使用new运算符创建类型参数的实例；但类型参数为此必须受构造函数约束。new()约束可以让编译器知道：提供的任何类型参数都必须具有可访问的无参数构造函数。
    /// </summary>
    /// <typeparam name="TType"></typeparam>
    public class BaseSqlDAL<TKey, TType> : IBaseSqlDAL<TKey, TType>
        where TType : BusinessSql<TKey, TType>, new()
        where TKey : IComparable
    {
        #region 基本属性方法
        private string _strPrimaryKey = "";
        private string _strTableName = "";
        private TType t = BusinessSql<TKey, TType>.SModel;

        /// <summary>
        /// 要连接的数据库名
        /// </summary>
        public string strConName
        {
            get { return BaseAccessHelper.getConnName(t.DataBaseName); }
        }

        /// <summary>
        /// 主键字段名
        /// </summary>
        public string strPrimaryKey
        {
            get
            {
                if (_strPrimaryKey == "")
                    _strPrimaryKey = t.PrimaryKey;
                return _strPrimaryKey;
            }
            set { _strPrimaryKey = value; }
        }

        /// <summary>
        /// 数据表名
        /// </summary>
        public string strTableName
        {
            get
            {
                if (_strTableName == "")
                    _strTableName = "[" + typeof(TType).Name + "]";
                return _strTableName;
            }
            set { _strTableName = value; }
        }
        #endregion

        #region Helper
        private static List<SqlParameter> parmsAll = null;
        /// <summary>
        /// 存储过程参数
        /// </summary>
        public List<SqlParameter> GetParmsList()
        {
            if (parmsAll != null)
                return parmsAll;
            try
            {
                if (t.GetParmsList() != null)
                    parmsAll = t.GetParmsList();
                else
                    parmsAll = GetParmsAll();
            }
            catch
            {
                parmsAll = GetParmsAll();
            }
            return parmsAll;
        }
        /// <summary>
        /// 获得所有的参数列表 基于sqlserver的
        /// </summary>
        /// <returns></returns>
        public List<SqlParameter> GetParmsAll()
        {
            PropertyInfo[] pis = t.GetPropertyInfo();
            if (parmsAll == null)
            {
                StringBuilder sbCloumnName = new StringBuilder();
                StringBuilder sbParameter = new StringBuilder();
                for (int i = 0; i < pis.Length; i++)
                {
                    SqlParameter parm = new SqlParameter();
                    parm.ParameterName = pis[i].Name;
                    parm.DbType = BaseAccessHelper.GetDbType(pis[i].PropertyType);
                    parmsAll.Add(parm);
                }
            }
            return parmsAll;
        }
        #endregion

        #region GetParms

        /// <summary>
        /// 获得的参数列表\操作语句
        /// </summary>
        /// <returns></returns>
        public List<SqlParameter> GetParms(TType tmodel, string strCloumnName, DataAction action, ref string strCommandText)
        {
            PropertyInfo[] pis = t.GetPropertyInfo();
            List<SqlParameter> parms = new List<SqlParameter>();
            StringBuilder sbCloumnName = new StringBuilder();
            StringBuilder sbParameter = new StringBuilder();
            StringBuilder sbSql = new StringBuilder();
            strCloumnName = string.IsNullOrEmpty(strCloumnName) ? "*" : strCloumnName.Trim();
            string[] strArr = strCloumnName.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            foreach (var item in pis)
            {
                if (t.HasIdentityPK && t.PrimaryKey == item.Name)
                    continue;
                if (!item.CanWrite)
                    continue;

                if (strCloumnName != "*")
                {
                    string strName = strArr.FirstOrDefault(str => str.ToLower() == item.Name.ToLower());
                    if (string.IsNullOrEmpty(strName))
                        continue;
                }

                SqlParameter parm = t.GetParmsList().FirstOrDefault(o => o.SourceColumn == item.Name);

                if (parm == null)
                    continue;

                sbCloumnName.AppendFormat("[{0}],", item.Name);
                sbParameter.AppendFormat("@{0},", item.Name);
                sbSql.AppendFormat("[{0}] = @{0},", item.Name);

                parm.Value = item.GetValue(tmodel, null);
                parms.Add(parm);
            }
            if (parms.Count == 0)
                throw new ArgumentException("初始化失败，获取存储过程参数失败。");

            sbCloumnName = sbCloumnName.Replace(",", "", sbCloumnName.Length - 1, 1);
            sbParameter = sbParameter.Replace(",", "", sbParameter.Length - 1, 1);
            sbSql = sbSql.Replace(",", "", sbSql.Length - 1, 1);
            switch (action)
            {
                case DataAction.Create:
                    strCommandText = string.Format("INSERT INTO {0} ({1}) VALUES ({2});SELECT IDENT_CURRENT('{0}');", strTableName, sbCloumnName, sbParameter);
                    break;
                case DataAction.CreateList:
                    strCommandText = string.Format("INSERT INTO {0} ({1}) VALUES ({2});", strTableName, sbCloumnName, sbParameter);
                    break;
                case DataAction.Update:
                case DataAction.UpdateList:
                    {
                        strCommandText = string.Format("UPDATE {0} SET {1} WHERE {2} = @{2}", strTableName, sbSql, strPrimaryKey);
                        SqlParameter parm = t.GetParmsList().FirstOrDefault(o => o.SourceColumn == strPrimaryKey);//将主键字段加入到参数列表中
                        PropertyInfo pi = pis.FirstOrDefault(o => o.Name == strPrimaryKey);
                        if (parm == null || pi == null)
                        {
                            parm = new SqlParameter();
                            parm.ParameterName = string.Format("@{0}", strPrimaryKey);
                            parm.SqlDbType = SqlDbType.Int;
                            parm.SourceColumn = strPrimaryKey;
                            parm.Value = pi.GetValue(tmodel, null);
                            parms.Add(parm);
                        }
                        else
                        {
                            parm.Value = pi.GetValue(tmodel, null);
                            parms.Add(parm);
                        }
                    }
                    break;
            }
            return parms;
        }

        #endregion

        #region GetCount
        /// <summary>
        /// 获得记录数
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        public virtual int GetCount(string strWhere)
        {
            string strSQL = string.Format("SELECT COUNT(0) FROM {0}", this.strTableName);
            if (!string.IsNullOrEmpty(strWhere))
                strSQL += string.Format(" WHERE {0}", strWhere);

            object obj = SQLHelper.ExecuteScalar(BaseAccessHelper.GetSqlConnectionString(t.DataBaseName), CommandType.Text, strSQL, null);
            return Convert.ToInt32(obj);
        }
        #endregion

        #region Exits
        /// <summary>
        /// 判断记录是否存在
        /// </summary>
        /// <param name="intID">主键ID</param>
        /// <returns></returns>
        public virtual bool Exists(TKey intID)
        {
            return Exists(string.Format("[{0}] = {1}", strPrimaryKey, BaseAccessHelper.GetQueryVal(typeof(TKey), intID)));
        }

        /// <summary>
        /// 判断记录是否存在
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        public virtual bool Exists(string strWhere)
        {
            return Exists(strWhere, strTableName);
        }

        /// <summary>
        /// 判断记录是否存在
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        /// <param name="sTableName">表名</param>
        internal bool Exists(string strWhere, string strTableName)
        {
            StringBuilder sbSql = new StringBuilder();
            sbSql.AppendFormat("SELECT COUNT(1) FROM {0}", strTableName);
            if (!string.IsNullOrEmpty(strWhere))
                sbSql.AppendFormat(" WHERE {0}", strWhere);

            object obj = SQLHelper.ExecuteScalar(BaseAccessHelper.GetSqlConnectionString(t.DataBaseName), CommandType.Text, sbSql.ToString(), null);

            int cmdresult = 0;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                cmdresult = 0;
            else
                cmdresult = int.Parse(obj.ToString());

            if (cmdresult == 0)
                return false;
            else
                return true;
        }
        #endregion

        #region Add
        /// <summary>
        /// 批量添加记录
        /// </summary>
        /// <param name="list">存储实体类的List</param>
        public virtual int Add(List<TType> list)
        {
            return AddList(list);
        }

        /// <summary>
        /// 批量添加记录
        /// </summary>
        /// <param name="dt">包含记录的DataTable</param>
        public virtual int Add(DataTable dt)
        {
            List<TType> list = new List<TType>();
            foreach (DataRowView drv in dt.DefaultView)
            {
                list.Add(GetModel(drv));
            }
            return AddList(list);
        }

        /// <summary>
        /// 批量添加记录
        /// </summary>
        /// <param name="dr">包含记录的DataReader</param>
        public virtual int Add(IDataReader dr)
        {
            List<TType> list = new List<TType>();
            while (dr.Read())
            {
                list.Add(GetModel(dr));
            }
            return AddList(list);
        }

        /// <summary>
        /// 添加单条记录，返回当前插入的这条记录的ID
        /// </summary>
        /// <param name="model">实体层某实体的实例</param>
        public virtual int Add(TType model)
        {
            PropertyInfo[] pis = t.GetPropertyInfo();

            string strCommandText = string.Empty;
            SqlParameter[] parms = GetParms(model, "*", DataAction.Create, ref  strCommandText).ToArray();
            object val = SQLHelper.ExecuteScalar(BaseAccessHelper.GetSqlConnectionString(t.DataBaseName), CommandType.Text, strCommandText, parms);
            return Convert.ToInt32(val);
        }

        /// <summary>
        /// 批量添加记录 
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        internal int AddList(List<TType> list)
        {
            if (list == null || list.Count < 1)
                return 0;

            int intCount = 0;
            PropertyInfo[] pis = t.GetPropertyInfo();
            using (SqlConnection conn = new SqlConnection(BaseAccessHelper.GetSqlConnectionString(t.DataBaseName)))
            {
                foreach (TType model in list)
                {
                    string strCommandText = string.Empty;
                    SqlParameter[] parms = GetParms(model, "*", DataAction.Create, ref  strCommandText).ToArray();

                    if (conn.State != ConnectionState.Open)
                        conn.Open();
                    object val = SQLHelper.ExecuteScalar(conn, CommandType.Text, strCommandText, parms);

                    if (Convert.ToInt32(val) > 0)
                        intCount++;
                }
            }
            return intCount;
        }
        #endregion Add

        #region Update
        /// <summary>
        /// 批量更新记录
        /// </summary>
        /// <param name="dt">存储需要更新的记录的DataTable</param>
        public virtual int Update(DataTable dt)
        {
            return Update(dt, "");
        }

        /// <summary>
        /// 批量更新记录
        /// </summary>
        /// <param name="dt">存储需要更新的记录的DataTable</param>
        /// <param name="strColumnList">按逗号隔开的需要被更新的字段</param>
        /// <returns></returns>
        public virtual int Update(DataTable dt, string strColumnList)
        {
            List<TType> list = new List<TType>();
            foreach (DataRowView drv in dt.DefaultView)
            {
                list.Add(GetModel(drv));
            }
            return Update(list, strColumnList);
        }

        /// <summary>
        /// 批量更新记录
        /// </summary>
        /// <param name="list">存储需要更新的记录的List</param>
        public virtual int Update(List<TType> list)
        {
            return Update(list, "");
        }

        /// <summary>
        /// 批量更新记录
        /// </summary>
        /// <param name="list">存储需要更新的记录的List</param>
        /// <param name="strColList">按逗号隔开的需要被更新的字段</param>
        /// <returns></returns>
        public virtual int Update(List<TType> list, string strColList)
        {
            return UpdateList(list, strColList);
        }

        /// <summary>
        /// 更新记录
        /// </summary>
        /// <param name="model">需要更新到数据库的实体类</param>
        public virtual bool Update(TType model)
        {
            return Update(model, "");
        }



        /// <summary>
        /// 更新记录
        /// </summary>
        /// <param name="model">需要更新到数据库的实体类</param>
        /// <param name="strColumnList">需要更新的字段</param>
        public virtual bool Update(TType model, string strColumnList)
        {
            PropertyInfo[] pis = t.GetPropertyInfo();

            List<SqlParameter> parms = new List<SqlParameter>();
            string strCommandText = string.Empty;
            parms = GetParms(model, strColumnList, DataAction.Update, ref  strCommandText);
            int val = SQLHelper.ExecuteNonQuery(BaseAccessHelper.GetSqlConnectionString(t.DataBaseName), CommandType.Text, strCommandText, parms.ToArray());

            return val > 0 ? true : false;
        }

        /// <summary>
        /// 批量更新记录
        /// </summary>
        /// <param name="list">存储需要更新的记录的List</param>
        /// <param name="strColumnList">按逗号隔开的需要被更新的字段</param>
        /// <returns></returns>
        internal int UpdateList(List<TType> list, string strColumnList)
        {
            if (list == null || list.Count < 1)
                return 0;

            int intCount = 0;
            PropertyInfo[] pis = t.GetPropertyInfo();
            using (SqlConnection conn = new SqlConnection(BaseAccessHelper.GetSqlConnectionString(t.DataBaseName)))
            {
                foreach (TType model in list)
                {
                    if (model == null)
                        continue;

                    string strCommandText = string.Empty;
                    List<SqlParameter> parms = GetParms(model, strColumnList, DataAction.Update, ref strCommandText);

                    if (conn.State != ConnectionState.Open)
                        conn.Open();

                    int val = SQLHelper.ExecuteNonQuery(conn, CommandType.Text, strCommandText, parms.ToArray());

                    if (val > 0)
                        intCount++;
                }
            }
            return intCount;
        }
        #endregion Update

        #region Delete
        /// <summary>
        /// 删除记录
        /// </summary>
        /// <param name="intID">记录ID</param>
        public virtual int Delete(TKey intID)
        {
            return Delete(new List<TKey>() { intID });
        }

        /// <summary>
        /// 删除记录
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        public virtual int Delete(string strWhere)
        {
            StringBuilder sbSql = new StringBuilder();
            sbSql.AppendFormat("DELETE {0}", strTableName);
            if (!string.IsNullOrEmpty(strWhere))
                sbSql.AppendFormat(" WHERE {0}", strWhere);

            int val = SQLHelper.ExecuteNonQuery(BaseAccessHelper.GetSqlConnectionString(t.DataBaseName), CommandType.Text, sbSql.ToString(), null);
            return val;
        }

        /// <summary>
        /// 批量删除记录
        /// </summary>
        /// <param name="list">主键ID的集合</param>
        /// <returns></returns>
        public virtual int Delete(List<TKey> list)
        {
            int intCount = 0;
            using (SqlConnection conn = new SqlConnection(BaseAccessHelper.GetSqlConnectionString(t.DataBaseName)))
            {
                foreach (var obj in list)
                {
                    string sbSql = string.Format("DELETE {0} WHERE [{1}] = {2}", strTableName, strPrimaryKey, BaseAccessHelper.GetQueryVal(typeof(TKey), obj));

                    if (conn.State != ConnectionState.Open)
                        conn.Open();
                    int val = SQLHelper.ExecuteNonQuery(BaseAccessHelper.GetSqlConnectionString(t.DataBaseName), CommandType.Text, sbSql, null);
                    if (val > 0)
                        intCount++;
                }
            }
            return intCount;
        }
        #endregion

        #region GetModel
        /// <summary>
        /// 获得一个Model对象实例
        /// </summary>
        /// <param name="intID">主键ID的值</param>
        public virtual TType GetModel(TKey intID)
        {
            return GetModel(intID, "*");
        }

        /// <summary>
        /// 获得一个Model对象实例
        /// </summary>
        /// <param name="intID">主键ID的值</param>
        /// <param name="strColumnList">以逗号分隔的查询字段名称</param>
        public virtual TType GetModel(TKey intID, string strColumnList)
        {
            string strWhere = string.Format("[{0}] = {1}", strPrimaryKey, BaseAccessHelper.GetQueryVal(typeof(TKey), intID));
            return GetModel(strWhere, strColumnList, "", false);
        }

        /// <summary>
        /// 获得一个Model对象实例
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        public virtual TType GetModel(string strWhere)
        {
            return GetModel(strWhere, "*");
        }

        /// <summary>
        /// 获得一个Model对象实例
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        /// <param name="strColumnList">以逗号分隔的查询字段名称</param>
        public virtual TType GetModel(string strWhere, string strColumnList)
        {
            return GetModel(strWhere, strColumnList, true);
        }

        /// <summary>
        /// 获得一个Model对象实例
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        /// <param name="strColumnList">以逗号分隔的查询字段名称</param>
        /// <param name="blOrderType">排序类型 true=降序 false=升序</param>
        /// <returns></returns>
        public virtual TType GetModel(string strWhere, string strColumnList, bool blOrderType)
        {
            return GetModel(strWhere, strColumnList, strPrimaryKey, blOrderType);
        }

        /// <summary>
        /// 获得一个Model对象实例
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        /// <param name="strColumnList">以逗号分隔的查询字段名称</param>
        /// <param name="strOrderColumn">以逗号分隔的排序字段名称</param>
        /// <param name="blOrderType">排序类型 true=降序 false=升序</param>
        /// <returns></returns>
        public virtual TType GetModel(string strWhere, string strColumnList, string strOrderColumn, bool blOrderType)
        {
            StringBuilder sbSql = new StringBuilder();
            sbSql.AppendFormat("SELECT TOP 1 {0} FROM {1}", string.IsNullOrEmpty(strColumnList) ? BaseAccessHelper.GetSQLFildList(strColumnList) : "*", strTableName);
            if (!string.IsNullOrEmpty(strWhere))
                sbSql.AppendFormat(" WHERE {0}", strWhere);
            if (!string.IsNullOrEmpty(strOrderColumn))
                sbSql.AppendFormat(" ORDER BY {0} {1}", strOrderColumn, blOrderType ? "DESC" : "ASC");

            TType model = default(TType);
            using (IDataReader dr = SQLHelper.ExecuteReader(BaseAccessHelper.GetSqlConnectionString(t.DataBaseName), CommandType.Text, sbSql.ToString(), null))
            {
                if (dr.Read())
                    model = GetModel(dr);
            }
            return model;
        }

        /// <summary>
        /// 获得一个Model对象实例
        /// </summary>
        /// <param name="dr">一个数据行</param>
        /// <returns></returns>
        public virtual TType GetModel(DataRow dr)
        {
            TType model = new TType();
            PropertyInfo[] pis = t.GetPropertyInfo();

            foreach (PropertyInfo pi in pis)
            {
                if (!pi.CanWrite || !pi.CanRead)
                    continue;

                try
                {
                    if (dr[pi.Name].ToString() != "")
                        pi.SetValue(model, dr[pi.Name], null);
                }
                catch (ArgumentException)
                {
                    continue;
                }
            }
            return model;
        }

        /// <summary>
        /// 获得一个Model对象实例
        /// </summary>
        /// <param name="drv">一个数据行视图</param>
        public virtual TType GetModel(DataRowView drv)
        {
            TType model = new TType();
            PropertyInfo[] pis = t.GetPropertyInfo();

            foreach (PropertyInfo pi in pis)
            {
                if (!pi.CanWrite || !pi.CanRead)
                    continue;

                try
                {
                    if (drv[pi.Name].ToString() != "")
                        pi.SetValue(model, drv[pi.Name], null);

                }
                catch (ArgumentException)
                { continue; }
            }
            return model;
        }

        /// <summary>
        /// 获得一个Model对象实例
        /// </summary>
        /// <param name="dr">一个IDataReader</param>
        /// <returns></returns>
        public virtual TType GetModel(IDataReader dr)
        {
            TType model = new TType();
            PropertyInfo[] pis = t.GetPropertyInfo();

            int intIndex;

            foreach (PropertyInfo pi in pis)
            {
                if (!pi.CanWrite || !pi.CanRead)
                    continue;

                try
                {
                    intIndex = dr.GetOrdinal(pi.Name);
                }
                catch (IndexOutOfRangeException)
                { continue; }
                if (dr.IsDBNull(intIndex))
                    continue;
                pi.SetValue(model, dr.GetValue(intIndex), null);
            }
            return model;
        }
        #endregion GetModel

        #region  GetList
        /// <summary>
        /// 获得数据集（数据集上限为500条数据）
        /// </summary>
        /// <returns></returns>
        public virtual List<TType> GetList()
        {
            return GetList("");
        }

        /// <summary>
        /// 获得数据集（数据集上限为500条数据）
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        public virtual List<TType> GetList(string strWhere)
        {
            return GetList(strWhere, 500, 1);
        }

        /// <summary>
        /// 获得数据集
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        /// <param name="intPageSize">每页显示记录数</param>
        /// <param name="intPageIndex">当前页码</param>
        public virtual List<TType> GetList(string strWhere, int intPageSize, int intPageIndex)
        {
            return GetList(strWhere, intPageSize, intPageIndex, "*");
        }

        /// <summary>
        /// 获得数据集
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        /// <param name="intPageSize">每页显示记录数</param>
        /// <param name="intPageIndex">当前页码</param>
        /// <param name="strColumnList">以逗号分隔的查询字段名称</param>
        /// <returns></returns>
        public virtual List<TType> GetList(string strWhere, int intPageSize, int intPageIndex, string strColumnList)
        {
            return GetList(strWhere, intPageSize, intPageIndex, strColumnList, true);
        }

        /// <summary>
        /// 获得数据集
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        /// <param name="intPageSize">每页显示记录数</param>
        /// <param name="intPageIndex">当前页码</param>
        /// <param name="strColumnList">以逗号分隔的查询字段名称</param>
        /// <param name="blOrderType">排序规则(true-降序；flase-升序)</param>
        /// <returns></returns>
        public virtual List<TType> GetList(string strWhere, int intPageSize, int intPageIndex, string strColumnList, bool blOrderType)
        {
            return GetList(strWhere, intPageSize, intPageIndex, blOrderType, strColumnList, strPrimaryKey);
        }

        /// <summary>
        /// 获得数据集
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        /// <param name="intPageSize">每页显示记录数</param>
        /// <param name="intPageIndex">当前页码</param>
        /// <param name="blOrderType">排序规则(true-降序；flase-升序)</param>
        public virtual List<TType> GetList(string strWhere, int intPageSize, int intPageIndex, bool blOrderType)
        {
            return GetList(strWhere, intPageSize, intPageIndex, blOrderType, strPrimaryKey);
        }

        /// <summary>
        /// 获得数据集
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        /// <param name="intPageSize">每页显示记录数</param>
        /// <param name="intPageIndex">当前页码</param>
        /// <param name="blOrderType">排序规则(true-降序；flase-升序)</param>
        /// <param name="strOrderColumn">以逗号分隔的排序字段名称</param>
        /// <returns></returns>
        public virtual List<TType> GetList(string strWhere, int intPageSize, int intPageIndex, bool blOrderType, string strOrderColumn)
        {
            return GetList(strWhere, intPageSize, intPageIndex, blOrderType, "*", strOrderColumn);
        }

        /// <summary>
        /// 获得数据集
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        /// <param name="intPageSize">每页显示记录数</param>
        /// <param name="intPageIndex">当前页码</param>
        /// <param name="strColumnList">以逗号分隔的查询字段名称</param>
        /// <param name="strOrderColumn">以逗号分隔的排序字段名称</param>
        /// <param name="blOrderType">排序规则(true-降序；flase-升序)</param>
        /// <returns></returns>
        public virtual List<TType> GetList(string strWhere, int intPageSize, int intPageIndex, bool blOrderType, string strColumnList, string strOrderColumn)
        {
            return GetList(strWhere, intPageSize, intPageIndex, strColumnList, strOrderColumn, blOrderType, strTableName);
        }

        /// <summary>
        /// 获得数据集
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        /// <param name="intPageSize">每页显示记录数</param>
        /// <param name="intPageIndex">当前页码</param>
        /// <param name="strColumnList">以逗号分隔的查询字段名称</param>
        /// <param name="strOrderColumn">以逗号分隔的排序字段名称</param>
        /// <param name="blOrderType">排序规则(true-降序；flase-升序)</param>
        /// <param name="strTableName">表名</param>
        /// <returns></returns>
        internal List<TType> GetList(string strWhere, int intPageSize, int intPageIndex, string strColumnList, string strOrderColumn, bool blOrderType, string strTableName)
        {
            List<TType> list = null;
            string strSQL = SYSequenceDAL.BuildSql(strWhere, intPageSize, intPageIndex, blOrderType, strColumnList, strOrderColumn, strTableName);
            DataTable dt = SQLHelper.ExecuteAdapter(BaseAccessHelper.GetSqlConnectionString(t.DataBaseName), CommandType.Text, strSQL, strTableName , null).Tables[0];
            list = GetList(dt);
            return list;
        }

        /// <summary>
        /// 获得数据集
        /// </summary>
        /// <param name="strSQL">SQL句子</param>
        public virtual List<TType> GetListByQuery(string strSQL)
        {
            List<TType> list = null;
            DataTable dt = SQLHelper.ExecuteAdapter(BaseAccessHelper.GetSqlConnectionString(t.DataBaseName), CommandType.Text, strSQL, strTableName, null).Tables[0];
            list = GetList(dt);
            return list;
        }

        /// <summary>
        /// 获取数据集
        /// </summary>
        /// <param name="dt">一个数据表</param>
        /// <returns></returns>
        public virtual List<TType> GetList(DataTable dt)
        {
            List<TType> list = new List<TType>();
            foreach (DataRowView drv in dt.DefaultView)
            {
                list.Add(GetModel(drv));
            }
            return list;
        }

        /// <summary>
        /// 获取数据集
        /// </summary>
        /// <param name="dr">一个IDataReader</param>
        /// <returns></returns>
        public virtual List<TType> GetList(IDataReader dr)
        {
            List<TType> list = new List<TType>();
            while (dr.Read())
            {
                list.Add(GetModel(dr));
            }
            return list;
        }

        /// <summary>
        /// 获取数据集
        /// </summary>
        /// <param name="dv">一个数据视图</param>
        /// <returns></returns>
        public virtual List<TType> GetList(DataView dv)
        {
            List<TType> list = new List<TType>();
            foreach (DataRowView drv in dv)
            {
                list.Add(GetModel(drv));
            }
            return list;
        }

        /// <summary>
        /// 返回TType列表。
        /// </summary>
        public virtual List<TType> GetList(SearchQuery query)
        {
            List<TType> list = null;
            DataTable dt = GetDataTable(query);
            list = GetList(dt);
            return list;
        }
        #endregion

        #region  GetResult
        /// <summary>
        /// 返回模型搜索结果集
        /// </summary>
        public virtual SearchResult<TType> GetResult(SearchQuery query)
        {
            SearchResult<TType> list = new SearchResult<TType>(query);
            DataTable dt = GetDataTable(query);
            list.Records = GetList(dt);

            string strSQL = string.Format("SELECT COUNT(1) FROM {0}", query.StrTableName);
            if (!string.IsNullOrEmpty(query.StrFilter))
                strSQL += string.Format(" WHERE {0}", query.StrFilter);
            object val = SQLHelper.ExecuteScalar(BaseAccessHelper.GetSqlConnectionString(t.DataBaseName), CommandType.Text, strSQL, null);
            list.TotalRecords = Convert.ToInt32(val);

            return list;
        }

        /// <summary>
        /// 获得数据集
        /// </summary>
        public DataSet GetDataSet(SearchQuery query)
        {
            if (string.IsNullOrEmpty(query.StrTableName))
                query.StrTableName = "[" + typeof(TType).Name + "]";

            return SQLHelper.ExecuteAdapter(BaseAccessHelper.GetSqlConnectionString(t.DataBaseName), CommandType.Text, query.GetQuery, strTableName, null);
        }

        /// <summary>
        /// 获得数据集
        /// </summary>
        public DataTable GetDataTable(SearchQuery query)
        {
            return GetDataSet(query).Tables[0];
        }
        #endregion

        #region  GetDataTable
        /// <summary>
        /// 获得数据集
        /// </summary>
        /// <returns></returns>
        public virtual DataTable GetDataTable()
        {
            return GetDataTable("");
        }

        /// <summary>
        /// 获得数据集
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        public virtual DataTable GetDataTable(string strWhere)
        {
            return GetDataTable(strWhere, 500, 1);
        }

        /// <summary>
        /// 获得数据集
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        /// <param name="intPageSize">每页显示记录数</param>
        /// <param name="intPageIndex">当前页码</param>
        public virtual DataTable GetDataTable(string strWhere, int intPageSize, int intPageIndex)
        {
            return GetDataTable(strWhere, intPageSize, intPageIndex, true);
        }

        /// <summary>
        /// 获得数据集
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        /// <param name="intPageSize">每页显示记录数</param>
        /// <param name="intPageIndex">当前页码</param>
        /// <param name="blOrderType">排序规则(true-降序；flase-升序)</param>
        public virtual DataTable GetDataTable(string strWhere, int intPageSize, int intPageIndex, bool blOrderType)
        {
            return GetDataTable(strWhere, intPageSize, intPageIndex, blOrderType, "*");
        }

        /// <summary>
        /// 获得数据集
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        /// <param name="intPageSize">每页显示记录数</param>
        /// <param name="intPageIndex">当前页码</param>
        /// <param name="blOrderType">排序规则(true-降序；flase-升序)</param>
        /// <param name="strColumnList">以逗号分隔的查询字段名称</param>
        public virtual DataTable GetDataTable(string strWhere, int intPageSize, int intPageIndex, bool blOrderType, string strColumnList)
        {
            return GetDataTable(strWhere, intPageSize, intPageIndex, blOrderType, strColumnList, strPrimaryKey);
        }

        /// <summary>
        /// 获得数据集
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        /// <param name="intPageSize">每页显示记录数</param>
        /// <param name="intPageIndex">当前页码</param>
        /// <param name="blOrderType">排序规则(true-降序；flase-升序)</param>
        /// <param name="strColumnList">以逗号分隔的查询字段名称</param>
        /// <param name="strOrderColumn">排序字段</param>
        public virtual DataTable GetDataTable(string strWhere, int intPageSize, int intPageIndex, bool blOrderType, string strColumnList, string strOrderColumn)
        {
            return GetDataTable(strWhere, intPageSize, intPageIndex, blOrderType, strColumnList, strOrderColumn, strTableName);
        }

        /// <summary>
        /// 获得数据集
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        /// <param name="intPageSize">每页显示记录数</param>
        /// <param name="intPageIndex">当前页码</param>
        /// <param name="blOrderType">排序规则(true-降序；flase-升序)</param>
        /// <param name="strColumnList">以逗号分隔的查询字段名称</param>
        /// <param name="strOrderColumn">排序字段</param>
        /// <param name="sTableName">表名</param>
        internal DataTable GetDataTable(string strWhere, int intPageSize, int intPageIndex, bool blOrderType, string strColumnList, string strOrderColumn, string sTableName)
        {
            string strSQL = SYSequenceDAL.BuildSql(strWhere, intPageSize, intPageIndex, blOrderType, strColumnList, strOrderColumn, strTableName);
            return SQLHelper.ExecuteAdapter(BaseAccessHelper.GetSqlConnectionString(t.DataBaseName), CommandType.Text, strSQL, strTableName, null).Tables[0];
        }
        #endregion GetDataTable

        #region  GetReader
        /// <summary>
        /// 获得数据集
        /// </summary>
        /// <returns></returns>
        public IDataReader GetReader()
        {
            return GetReader("");
        }

        /// <summary>
        /// 获得数据集
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        public virtual IDataReader GetReader(string strWhere)
        {
            return GetReader(strWhere, 500, 1);
        }

        /// <summary>
        /// 获得数据集
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        /// <param name="intPageSize">每页显示记录数</param>
        /// <param name="intPageIndex">当前页码</param>
        public virtual IDataReader GetReader(string strWhere, int intPageSize, int intPageIndex)
        {
            return GetReader(strWhere, intPageSize, intPageIndex, true);
        }

        /// <summary>
        /// 获得数据集
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        /// <param name="intPageSize">每页显示记录数</param>
        /// <param name="intPageIndex">当前页码</param>
        /// <param name="blOrderType">排序规则(true-降序；flase-升序)</param>
        public virtual IDataReader GetReader(string strWhere, int intPageSize, int intPageIndex, bool blOrderType)
        {
            return GetReader(strWhere, intPageSize, intPageIndex, blOrderType, "*");
        }

        /// <summary>
        /// 获得数据集
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        /// <param name="intPageSize">每页显示记录数</param>
        /// <param name="intPageIndex">当前页码</param>
        /// <param name="blOrderType">排序规则(true-降序；flase-升序)</param>
        /// <param name="strColumnList">以逗号分隔的查询字段名称</param>
        public virtual IDataReader GetReader(string strWhere, int intPageSize, int intPageIndex, bool blOrderType, string strColumnList)
        {
            return GetReader(strWhere, intPageSize, intPageIndex, blOrderType, strColumnList, strPrimaryKey);
        }

        /// <summary>
        /// 获得数据集
        /// </summary>
        /// <param name="strWhere">Where子句</param>
        /// <param name="intPageSize">每页显示记录数</param>
        /// <param name="intPageIndex">当前页码</param>
        /// <param name="blOrderType">排序规则(true-降序；flase-升序)</param>
        /// <param name="strColumnList">以逗号分隔的查询字段名称</param>
        /// <param name="strOrderColumn">排序字段</param>
        public virtual IDataReader GetReader(string strWhere, int intPageSize, int intPageIndex, bool blOrderType, string strColumnList, string strOrderColumn)
        {
            return GetReader(strWhere, intPageSize, intPageIndex, blOrderType, strColumnList, strOrderColumn, strTableName);
        }

        internal IDataReader GetReader(string strWhere, int intPageSize, int intPageIndex, bool blOrderType, string strColumnList, string strOrderColumn, string sTableName)
        {
            string strSQL = SYSequenceDAL.BuildSql(strWhere, intPageSize, intPageIndex, blOrderType, strColumnList, strOrderColumn, strTableName);
            return SQLHelper.ExecuteReader(BaseAccessHelper.GetSqlConnectionString(t.DataBaseName), CommandType.Text, strSQL, null);
        }
        #endregion  GetReader

        #region 序列化
        /// <summary>
        /// 对象序列化
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string Serialize(TType model)
        {
            if (model == null)
                return string.Empty;

            IFormatter formatter = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            formatter.Serialize(ms, model);
            ms.Seek(0, SeekOrigin.Begin);
            byte[] bt = new byte[ms.Length];
            ms.Read(bt, 0, bt.Length);
            ms.Close();
            return Convert.ToBase64String(bt);
        }

        /// <summary>
        /// 反序化为对象
        /// </summary>
        /// <param name="strBase64"></param>
        /// <returns></returns>
        public static TType Deserialize(string strBase64)
        {
            if (string.IsNullOrEmpty(strBase64))
                return null;

            TType obj = null;
            try
            {
                IFormatter formatter = new BinaryFormatter();
                byte[] bt = System.Convert.FromBase64String(strBase64);
                MemoryStream ms = new MemoryStream(bt);
                obj = formatter.Deserialize(ms) as TType;
                ms.Close();
            }
            catch (Exception ex) { }
            return obj;
        }
        #endregion


        #region 事务控制
        private void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;
            if (cmdParms != null)
            {


                foreach (SqlParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }

        /// <summary>
        /// 执行Sql事务
        /// </summary>
        /// <param name="list">SQL命令行列表</param>
        /// <returns>执行结果 0 由于SQL造成事务失败     1 整体事务执行成功</returns>
        public int SqlTran(List<CommandInfo> list)
        {
            using (SqlConnection conn = new SqlConnection(BaseAccessHelper.GetSqlConnectionString(t.DataBaseName)))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                SqlTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    foreach (var item in list)
                    {
                        #region
                        string cmdText = item.CommandText;
                        SqlParameter[] cmdParms = (SqlParameter[])item.Parameters;
                        PrepareCommand(cmd, conn, tx, cmdText, cmdParms);
                        if (item.EffentNextType == EffentNextType.SolicitationEvent)
                        {
                            #region
                            if (item.CommandText.ToLower().IndexOf("count(") == -1)
                            {
                                tx.Rollback();
                                throw new Exception("违背要求" + item.CommandText + "必须符合select count(..的格式");
                                //return 0;
                            }

                            object obj = cmd.ExecuteScalar();
                            bool isHave = false;
                            if (obj == null && obj == DBNull.Value)
                            {
                                isHave = false;
                            }
                            isHave = Convert.ToInt32(obj) > 0;
                            if (isHave)
                            {
                                //引发事件
                                item.OnSolicitationEvent();
                            }
                            #endregion
                        }
                        if (item.EffentNextType == EffentNextType.WhenHaveContine || item.EffentNextType == EffentNextType.WhenNoHaveContine)
                        {
                            #region
                            if (item.CommandText.ToLower().IndexOf("count(") == -1)
                            {
                                tx.Rollback();
                                throw new Exception("SQL:违背要求" + item.CommandText + "必须符合select count(..的格式");
                                //return 0;
                            }

                            object obj = cmd.ExecuteScalar();
                            bool isHave = false;
                            if (obj == null && obj == DBNull.Value)
                            {
                                isHave = false;
                            }
                            isHave = Convert.ToInt32(obj) > 0;

                            if (item.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
                            {
                                tx.Rollback();
                                throw new Exception("SQL:违背要求" + item.CommandText + "返回值必须大于0");
                                //return 0;
                            }
                            if (item.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
                            {
                                tx.Rollback();
                                throw new Exception("SQL:违背要求" + item.CommandText + "返回值必须等于0");
                                //return 0;
                            }
                            #endregion
                            continue;
                        }
                        int val = cmd.ExecuteNonQuery();
                        if (item.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0)
                        {
                            tx.Rollback();
                            throw new Exception("SQL:违背要求" + item.CommandText + "必须有影响行");
                            //return 0;
                        }
                        cmd.Parameters.Clear();
                        #endregion
                    }
                    tx.Commit();
                    return 1;
                }
                catch (System.Data.SqlClient.SqlException e)
                {
                    tx.Rollback();
                    throw e;
                }
                catch (Exception e)
                {
                    tx.Rollback();
                    throw e;
                }
            }
        }
        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>		
        public int SqlTran(List<String> list)
        {
            using (SqlConnection conn = new SqlConnection(BaseAccessHelper.GetSqlConnectionString(t.DataBaseName)))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                SqlTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    int count = 0;
                    foreach (var item in list)
                    {
                        if (string.IsNullOrEmpty(item))
                            continue;

                        cmd.CommandText = item;
                        count += cmd.ExecuteNonQuery();
                    }
                    tx.Commit();
                    return count;
                }
                catch
                {
                    tx.Rollback();
                    return 0;
                }
            }
        }
        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public int SqlTran(string strSQL, params SqlParameter[] cmdParms)
        {
            using (SqlConnection conn = new SqlConnection(BaseAccessHelper.GetSqlConnectionString(t.DataBaseName)))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, conn, null, strSQL, cmdParms);
                        int val = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return val;
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        throw e;
                    }
                }
            }
        }        
        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表（key为sql语句，value是该语句的SqlParameter[]）</param>
        public void SqlHsTran(Hashtable list)
        {
            using (SqlConnection conn = new SqlConnection(BaseAccessHelper.GetSqlConnectionString(t.DataBaseName)))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    SqlCommand cmd = new SqlCommand();
                    try
                    {
                        //循环
                        foreach (DictionaryEntry item in list)
                        {
                            string cmdText = item.Key.ToString();
                            SqlParameter[] cmdParms = (SqlParameter[])item.Value;
                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();
                        }
                        trans.Commit();
                    }
                    catch
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
        }
        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表（key为sql语句，value是该语句的SqlParameter[]）</param>
        public int SqlComTran(List<CommandInfo> cmdList)
        {
            using (SqlConnection conn = new SqlConnection(BaseAccessHelper.GetSqlConnectionString(t.DataBaseName)))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    SqlCommand cmd = new SqlCommand();
                    try
                    {
                        int count = 0;
                        //循环
                        foreach (CommandInfo item in cmdList)
                        {
                            string cmdText = item.CommandText;
                            SqlParameter[] cmdParms = (SqlParameter[])item.Parameters;
                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);

                            if (item.EffentNextType == EffentNextType.WhenHaveContine || item.EffentNextType == EffentNextType.WhenNoHaveContine)
                            {
                                if (item.CommandText.ToLower().IndexOf("count(") == -1)
                                {
                                    trans.Rollback();
                                    return 0;
                                }

                                object obj = cmd.ExecuteScalar();
                                bool isHave = false;
                                if (obj == null && obj == DBNull.Value)
                                {
                                    isHave = false;
                                }
                                isHave = Convert.ToInt32(obj) > 0;

                                if (item.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
                                {
                                    trans.Rollback();
                                    return 0;
                                }
                                if (item.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
                                {
                                    trans.Rollback();
                                    return 0;
                                }
                                continue;
                            }
                            int val = cmd.ExecuteNonQuery();
                            count += val;
                            if (item.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0)
                            {
                                trans.Rollback();
                                return 0;
                            }
                            cmd.Parameters.Clear();
                        }
                        trans.Commit();
                        return count;
                    }
                    catch
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
        }
        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表（key为sql语句，value是该语句的SqlParameter[]）</param>
        public void SqlTranWithIndentity(List<CommandInfo> SQLStringList)
        {
            using (SqlConnection conn = new SqlConnection(BaseAccessHelper.GetSqlConnectionString(t.DataBaseName)))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    SqlCommand cmd = new SqlCommand();
                    try
                    {
                        int indentity = 0;
                        //循环
                        foreach (CommandInfo item in SQLStringList)
                        {
                            string cmdText = item.CommandText;
                            SqlParameter[] cmdParms = (SqlParameter[])item.Parameters;
                            foreach (SqlParameter q in cmdParms)
                            {
                                if (q.Direction == ParameterDirection.InputOutput)
                                {
                                    q.Value = indentity;
                                }
                            }
                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            foreach (SqlParameter q in cmdParms)
                            {
                                if (q.Direction == ParameterDirection.Output)
                                {
                                    indentity = Convert.ToInt32(q.Value);
                                }
                            }
                            cmd.Parameters.Clear();
                        }
                        trans.Commit();
                    }
                    catch
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
        }
        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表（key为sql语句，value是该语句的SqlParameter[]）</param>
        public void SqlTranWithIndentity(Hashtable SQLStringList)
        {
            using (SqlConnection conn = new SqlConnection(BaseAccessHelper.GetSqlConnectionString(t.DataBaseName)))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    SqlCommand cmd = new SqlCommand();
                    try
                    {
                        int indentity = 0;
                        //循环
                        foreach (DictionaryEntry item in SQLStringList)
                        {
                            string cmdText = item.Key.ToString();
                            SqlParameter[] cmdParms = (SqlParameter[])item.Value;
                            foreach (SqlParameter q in cmdParms)
                            {
                                if (q.Direction == ParameterDirection.InputOutput)
                                {
                                    q.Value = indentity;
                                }
                            }
                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            foreach (SqlParameter q in cmdParms)
                            {
                                if (q.Direction == ParameterDirection.Output)
                                {
                                    indentity = Convert.ToInt32(q.Value);
                                }
                            }
                            cmd.Parameters.Clear();
                        }
                        trans.Commit();
                    }
                    catch
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
        }
        #endregion 事务控制
    }
}


public enum EffentNextType
{
    /// <summary>
    /// 对其他语句无任何影响 
    /// </summary>
    None,
    /// <summary>
    /// 当前语句必须为"select count(1) from .."格式，如果存在则继续执行，不存在回滚事务
    /// </summary>
    WhenHaveContine,
    /// <summary>
    /// 当前语句必须为"select count(1) from .."格式，如果不存在则继续执行，存在回滚事务
    /// </summary>
    WhenNoHaveContine,
    /// <summary>
    /// 当前语句影响到的行数必须大于0，否则回滚事务
    /// </summary>
    ExcuteEffectRows,
    /// <summary>
    /// 引发事件-当前语句必须为"select count(1) from .."格式，如果不存在则继续执行，存在回滚事务
    /// </summary>
    SolicitationEvent
}
public class CommandInfo
{
    event EventHandler _solicitationEvent;

    public object ShareObject = null;
    public object OriginalData = null;
    public string CommandText;
    public SqlParameter[] Parameters;
    public EffentNextType EffentNextType = EffentNextType.None;

    public CommandInfo()
    {

    }
    public CommandInfo(string sqlText, SqlParameter[] para)
    {
        this.CommandText = sqlText;
        this.Parameters = para;
    }
    public CommandInfo(string sqlText, SqlParameter[] para, EffentNextType type)
    {
        this.CommandText = sqlText;
        this.Parameters = para;
        this.EffentNextType = type;
    }

    public event EventHandler SolicitationEvent
    {
        add
        {
            _solicitationEvent += value;
        }
        remove
        {
            _solicitationEvent -= value;
        }
    }
    public void OnSolicitationEvent()
    {
        if (_solicitationEvent != null)
        {
            _solicitationEvent(this, new EventArgs());
        }
    }
}